/**
 * @description user service
 */

 const { User } =  require('../db/model')
 const { formatUser } = require('./_format')
 /**
  * 获取用户信息
  * @param {string} username 
  * @param {string} password 
  */
 async function getUserInfo(userName, password) {
    // 查询条件
    const whereOpt = {
        userName
    }
    if(password) {
        Object.assign(whereOpt, { password })
    }

    // 查询
    const result = await User.findOne({
        attributes: ['id', 'userName', 'nickName', 'picture', 'city', 'openid'],
        where: whereOpt
    })
    if(result == null) {
        // 未找到
        return result
    }

    // 格式化
    const formatRes = formatUser(result.dataValues)
    return formatRes
 }

 async function createUser({ userName, password, gender = 3, nickName }) {
    const result = await User.create({
        userName,
        password,
        nickName: nickName ? nickName: userName,
        gender
    })
    return result.dataValues
 }
 async function deleteUser( userName ) {
    const result = await User.destroy({
        where: {
            userName
        }
    })
    // result 删除的行数
    return result > 0
 }

 /**
  * 更新用户
  * @param {*} param0 
  * @param {*} param1 
  */
 async function updateUser({ newPassword, newNickName, newPicture, newCity, openid },
    { userName, password }) {
    const updateData ={}
    if(newPassword) {
        updateData.password = newPassword
    }
    if(newNickName) {
        updateData.nickName = newNickName
    }
    if(newPicture) {
        updateData.picture = newPicture
    }
    if(newCity) {
        updateData.city = newCity
    }
    if(openid) {
        updateData.openid = openid
    }
    // 拼接查询条件
    const whereData = {
        userName
    }
    if (password) {
        whereData.password = password
    }

    // 执行修改
    const result = await User.update(updateData, {
        where: whereData
    })

    return result[0] > 0
 }
 module.exports = {
    getUserInfo,
    createUser,
    deleteUser,
    updateUser
 }